<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2019/9/18
 * Time: 11:17
 */

namespace app\index\controller;


use think\Db;
use think\Exception;
use think\helper\Time;

class Lottery extends Base
{
    public $table = 'lottery';
    public $site_id;
    public $lottery;
    public function __construct()
    {
        parent::__construct();
        $id = input('id');

    }

    public function index()
    {
        $id = input('id');
        $this->checkLottery($id);
        $this->getSiteConfig();

        if(!$this->lottery)
            $this->error('活动不存在');

        $this->assign('lottery',$this->lottery);
        $this->assign('title',$this->lottery['name']);
        return $this->fetch();
    }

    public function info()
    {
        $id = input('id');
        $this->checkLottery($id);
        $this->getSiteConfig();

        if(!$this->lottery)
            $this->error('活动不存在');

        $nums = $this->getDrawTimes();
        $this->assign('lottery_json',json_encode($this->lottery,JSON_UNESCAPED_UNICODE));
        $this->assign('lottery',$this->lottery);
        $this->assign('nums',$nums);
        $this->assign('title',$this->lottery['name']);
        return $this->fetch();
    }

    /**
     * @return mixed
     * 我的中奖奖品列表
     */
    public function myList()
    {
        $id = input('id');
        $this->checkLottery($id);
        $this->getSiteConfig();
        if(!$this->lottery)
            $this->error('活动不存在');

        $this->assign('title',$this->lottery['name']);

        $this->assign('lottery',json_encode($this->lottery,JSON_UNESCAPED_UNICODE));
        return $this->fetch();
    }

    public function getMyPrize()
    {
        $id = input('id');
        $data = Db::name('lottery_data')
            ->alias('a')
            ->join('lottery_prize b','b.id=a.prize_id')
            ->where('a.lottery_id',$id)
            ->where('a.mobile',$this->mobile)
            ->where('a.prize_type','neq',1)
            ->order('a.id desc')
            ->field('a.*,b.name,b.img')
            ->select();
        if($data){
            foreach ($data as $key=>$value){
                $data[$key]['time'] = date('n',$value['addtime']).'月'.date('j',$value['addtime']).'日 '.date('H:i',$value['addtime']);
                $data[$key]['record'] = 0;
                if($value['prize_type'] == 2 && $value['status'] == 1){
                    $data[$key]['record'] = 1;
                }
            }
        }
        return dataReturn(1,'success',['list'=>$data]);
    }

    /**
     * 填写中奖资料
     */
    public function record()
    {
        $id = input('id');
        $data = Db::name('lottery_data')
            ->alias('a')
            ->join('lottery_prize b','b.id=a.prize_id')
            ->where('a.id',$id)
            ->where('a.mobile',$this->mobile)
            ->where('a.prize_type','neq',1)
            ->order('a.id desc')
            ->field('a.*,b.name,b.img')
            ->find();
        if(!$data)
            $this->error('奖品不存在');

        $this->checkLottery($data['lottery_id']);
        $this->getSiteConfig();
        if(!$this->lottery)
            $this->error('活动不存在');
        $this->assign('title',$this->lottery['name']);

        $data['link_name'] = $data['link_name']??'';
        $data['link_tel'] = $data['link_tel']??'';
        $data['link_address'] = $data['link_address']??'';
        $this->assign('prize',json_encode($data,JSON_UNESCAPED_UNICODE));
        return $this->fetch();
    }

    public function saveAddress()
    {
        $id = input('id');
        $model = [
            'status'=>2,
            'link_name'=>input('link_name'),
            'link_tel'=>input('link_tel'),
            'link_address'=>input('link_address'),
            'modtime'=>\time(),
        ];
        $res = Db::name('lottery_data')->where('id',$id)->where('mobile',$this->mobile)->update($model);
        if($res)
            return dataReturn(1,'保存成功');
        return dataReturn(0,'保存失败');
    }

    /**
     * 查询用户剩余抽奖次数
     */
    public function getDrawTimes()
    {
        $nums = 0;
        if(!$this->mobile)
            return $nums;
        if($this->lottery['lottery_type'] == 1){
            //每日
            $where['addtime'] = ['between',Time::today()];
        }else{
            //总数
            $where = '1=1';
        }
        $used = Db::name('lottery_data')
            ->where('lottery_id',$this->lottery['id'])
            ->where('mobile',$this->mobile)
            ->where($where)
            ->count('id');
        $total = $this->lottery['nums'];
        return $nums = $total - $used;
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获奖名单
     */
    public function getDrawData()
    {
        $page = input('page/d')?:1;
        $limit = input('limit/d')?:10;
        $lottery_id = input('id/d');
        $field = 'a.id,a.lottery_id,b.name,a.mobile';
        $data = Db::name('lottery_data')
            ->alias('a')
            ->join('lottery_prize b','b.id=a.prize_id')
            ->where('a.lottery_id',$lottery_id)
            ->where('a.prize_type', 'neq', 1)
            ->order('a.id desc')
            ->page($page,$limit)
            ->field($field)
            ->select();
        if($data){
            foreach ($data as &$value){
                $value['mobile'] = substr($value['mobile'],0,3).'****'.substr($value['mobile'],7);
            }
        }
        return dataReturn(1,'ok',['list'=>$data]);
    }

    /**
     * 抽奖
     */
    public function getLottery()
    {
//        return dataReturn(1,'尚未登陆');

        if(!$this->mobile)
            return dataReturn(1,'尚未登陆');
        $lottery_id = input('id/d');
        $lottery = $this->checkLottery($lottery_id);
        if(!$lottery)
            return dataReturn(2,'活动不存在');

        //查看活动时间
        $time = \time();
        if($time < $lottery['start'])
            return dataReturn(2,'活动尚未开始');
        if($time > $lottery['end'])
            return dataReturn(2,'活动已结束');


        $nums = $this->getDrawTimes();
        if($nums<1){
            return dataReturn(3,'抽奖次数不足');
        }
        $prize = Db::name('lottery_prize')
            ->where('lottery_id',$lottery_id)
            ->where('enable',1)
            ->select();
        $total = 0; //中奖的总值
        //中奖的礼物
        $draw_prize = null;
        if($prize){
            foreach ($prize as $key=>$value){
                if($value['type'] != 1 && $value['stock'] <= 0){
                    unset($prize[$key]);
                }else{
                    $total += $value['chance'];
                }
            }

            if($total){
                $i = 0;
                $bingo = mt_rand(1,$total);
                foreach ($prize as $key=>$value){
                    $i += $value['chance'];
                    if($bingo <= $i){
                        $draw_prize = $value;
                        break;
                    }
                }
            }
        }
        //存储中奖信息

        Db::startTrans();
        try{
            $model = [
                'site_id'=>$lottery['site_id'],
                'lottery_id'=>$lottery['id'],
                'prize_id'=>$draw_prize['id']??0,//不存在奖品
                'prize_type'=>$draw_prize['type']??1,//1为 未中奖
                'mobile'=>$this->mobile,
                'status'=>1,
                'addtime'=>$time,
                'modtime'=>$time,
            ];
            $res1 = Db::name('lottery_data')->insertGetId($model);
            $res2 = true;
            //实物和虚拟物品扣库存
            if($model['prize_type'] > 1){
                $res2 = Db::name('lottery_prize')->where('id',$draw_prize['id'])->dec('stock')->update(['modtime'=>$time]);
            }
            if($res1 && $res2){
                Db::commit();
                $prize_back = [
                    'data_id'=>$res1,
                    'prize_id'=>$draw_prize['id']??0,
                    'site_id'=>$lottery['site_id'],
                    'lottery_id'=>$draw_prize['id']??0,
                    'type'=>$draw_prize['type']??1,
                    'name'=>$draw_prize['name']??'',
                    'img'=>$draw_prize['img']??'',
                ];
                return dataReturn(0,'success',['prize'=>$prize_back]);
            }
            Db::rollback();
            return dataReturn(2,'服务器繁忙，请稍后再试');
        }catch (Exception $exception){
            trace('lottery_error:'.$exception->getMessage(),'error');
            Db::rollback();
            return dataReturn(2,'服务器繁忙，请稍后再试');
        }

    }

    public function checkLottery($id)
    {
        $lottery = Db::name($this->table)->where('id',$id)->where('enable',1)->find();
        $this->lottery = $lottery;
        $this->site_id = $this->lottery['site_id'];

        return $lottery;
    }
}
